import Vue from 'vue'
import axios from 'axios'
import router from '../router/router'
import qs from 'qs'
import merge from 'lodash/merge'
import { clearLoginInfo } from '@/utils'

// const BASE_URL = 'http://192.168.15.177:9000/gengyun';
// const BASE_URL = 'http://192.168.43.116:9000/gengyun';
// const BASE_URL = 'http://49.232.140.30:9000/gengyun';
const BASE_URL = 'http://localhost:9000/gengyun';
const http = axios.create({
    baseURL: BASE_URL, // api 的 base_url
    timeout: 100000, // request timeout //设置请求时长
    withCredentials: true,
    headers: {
        'Content-Type': 'application/json; charset=utf-8'
    }
})

http.interceptors.request.use(
    config => {
        config.headers['token'] = Vue.cookie.get('token') // 请求头带上token
        return config
    },
    error => {
        // Do something with request error
        // console.log(error) // for debug
        return Promise.reject(error)
    }
)

http.interceptors.response.use(
    response => {
        // response 根据不同status 状态返回 对应不同的comfirm
        if (response.data && response.data.code === 401) { // 401, token失效
            clearLoginInfo()
            router.push({name: 'login'}).then(r => {})
        }
        return response
    },
    error => {
        // console.log('err' + error) // for debug
        return Promise.reject(error)
    }
)

http.adornUrl = (actionName) => {
    // 非生产环境 && 开启代理, 接口前缀统一使用[/proxyApi/]前缀做代理拦截!
    return (process.env.NODE_ENV !== 'production' && process.env.OPEN_PROXY ? '/proxyApi/' : BASE_URL) + actionName
}

/**
 * get请求参数处理
 * @param {*} params 参数对象
 * @param {*} openDefultParams 是否开启默认参数?
 */
http.adornParams = (params = {}, openDefultParams = true) => {
    var defaults = {
        't': new Date().getTime()
    }
    return openDefultParams ? merge(defaults, params) : params
}


http.adornData = (data = {}, openDefultdata = true, contentType = 'json') => {
    var defaults = {
        't': new Date().getTime()
    }
    data = openDefultdata ? merge(defaults, data) : data
    return contentType === 'json' ? JSON.stringify(data) : qs.stringify(data)
}

export default http